package com.lagou.edu.user.controller;

import com.lagou.edu.api.IAuthCodeService;
import com.lagou.edu.common.bean.Response;
import com.lagou.edu.common.constant.ResponseCode;
import com.lagou.edu.common.pojo.User;
import com.lagou.edu.common.utils.ResponseUtil;
import com.lagou.edu.user.service.ITokenService;
import com.lagou.edu.user.service.IUserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * created by kirito at 2020/7/5
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private ITokenService tokenService;

    @Reference(check = false)
    private IAuthCodeService authCodeService;

    /**
     * 注册
     *
     * @param email           邮箱
     * @param password        密码
     * @param confirmPassword 确认密码
     * @param code            验证码
     * @return true/false
     */
    @PostMapping("/register/{email}/{password}/{confirmPassword}/{code}")
    public Response register(@PathVariable(value = "email") String email,
                             @PathVariable(value = "password") String password,
                             @PathVariable(value = "confirmPassword") String confirmPassword,
                             @PathVariable(value = "code") String code) {
        // 重复注册校验
        if (userService.isRegistered(email)) {
            return ResponseUtil.response(ResponseCode.REPEAT_REGISTRY_ERROR);
        }
        // 验证码校验
        int validate = authCodeService.validateCode(email, code);
        if (validate == 1) {
            return ResponseUtil.response(ResponseCode.AUTHCODE_IS_ERROR);
        } else if (validate == 2) {
            return ResponseUtil.response(ResponseCode.AUTHCODE_IS_TIMEOUT);
        }
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        user.setConfirmPassword(confirmPassword);
        userService.save(user);
        return ResponseUtil.response(ResponseCode.SUCCESS);
    }

    /**
     * 登录
     *
     * @param email    邮箱
     * @param password 密码
     * @return 邮箱
     */
    @PostMapping("/login/{email}/{password}")
    public Response login(@PathVariable(value = "email") String email,
                          @PathVariable(value = "password") String password,
                          HttpServletResponse response) {
        User user = userService.findByEmailAndPassword(email, password);
        if (user == null) {
            return ResponseUtil.response(ResponseCode.USERNAME_OR_PASSWORD_ERROR);
        }
        // 存在，可以登录，写入token并返回
        String token = tokenService.createToken();
        tokenService.saveToken(email, token);
        Cookie cookie = new Cookie("lagou-cookie", token);
        cookie.setPath("/");
        response.addCookie(cookie);
        return ResponseUtil.response(ResponseCode.SUCCESS);
    }

    /**
     * 是否已注册
     *
     * @param email 邮箱
     * @return true/false
     */
    @GetMapping("/isRegistered/{email}")
    public Response isRegistered(@PathVariable(value = "email") String email) {
        if (userService.isRegistered(email)) {
            return ResponseUtil.response(ResponseCode.REPEAT_REGISTRY_ERROR);
        }
        return ResponseUtil.response(ResponseCode.SUCCESS);
    }

    /**
     * 校验token是否合法
     *
     * @param token token
     * @return true/false
     */
    @GetMapping("/token/validate/{token}")
    public Response validateToken(@PathVariable(value = "token") String token) {
        if (userService.validateToken(token)) {
            return ResponseUtil.response(ResponseCode.TOKEN_IS_INVALIDED);
        }
        return ResponseUtil.response(ResponseCode.SUCCESS);
    }

    /**
     * 根据token查询⽤用户登录邮箱
     *
     * @param token token
     * @return 邮箱
     */
    @GetMapping("/info/{token}")
    public Response getEmail(@PathVariable(value = "token") String token) {
        String email = userService.findEmailByToken(token);
        return ResponseUtil.response(ResponseCode.SUCCESS, email);
    }

}
